const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const auth = require('../middleware/auth');

// @route   GET api/tasks
// @desc    Get all tasks for a user
// @access  Private
router.get('/', auth, async (req, res) => {
  try {
    const [tasks] = await pool.query(
      'SELECT * FROM tasks WHERE user_id = ? ORDER BY created_at DESC',
      [req.user.id]
    );
    
    res.json(tasks);
  } catch (err) {
    console.error(err.message);
    res.status(500).json({ message: '服务器错误' });
  }
});

// @route   POST api/tasks
// @desc    Create a task
// @access  Private
router.post('/', auth, async (req, res) => {
  const { title, description } = req.body;
  
  try {
    const [result] = await pool.query(
      'INSERT INTO tasks (title, description, user_id) VALUES (?, ?, ?)',
      [title, description, req.user.id]
    );
    
    const [newTask] = await pool.query(
      'SELECT * FROM tasks WHERE id = ?',
      [result.insertId]
    );
    
    res.status(201).json(newTask[0]);
  } catch (err) {
    console.error(err.message);
    res.status(500).json({ message: '添加任务失败' });
  }
});

// @route   PUT api/tasks/:id
// @desc    Update a task
// @access  Private
router.put('/:id', auth, async (req, res) => {
  const { title, description, status } = req.body;
  
  try {
    // Check if task exists and belongs to user
    const [tasks] = await pool.query(
      'SELECT * FROM tasks WHERE id = ? AND user_id = ?',
      [req.params.id, req.user.id]
    );
    
    if (tasks.length === 0) {
      return res.status(404).json({ message: '任务不存在或无权限' });
    }
    
    // Update task
    await pool.query(
      'UPDATE tasks SET title = ?, description = ?, status = ? WHERE id = ?',
      [title, description, status, req.params.id]
    );
    
    // Get updated task
    const [updatedTask] = await pool.query(
      'SELECT * FROM tasks WHERE id = ?',
      [req.params.id]
    );
    
    res.json(updatedTask[0]);
  } catch (err) {
    console.error(err.message);
    res.status(500).json({ message: '更新任务失败' });
  }
});

// @route   DELETE api/tasks/:id
// @desc    Delete a task
// @access  Private
router.delete('/:id', auth, async (req, res) => {
  try {
    // Check if task exists and belongs to user
    const [tasks] = await pool.query(
      'SELECT * FROM tasks WHERE id = ? AND user_id = ?',
      [req.params.id, req.user.id]
    );
    
    if (tasks.length === 0) {
      return res.status(404).json({ message: '任务不存在或无权限' });
    }
    
    // Delete task
    await pool.query('DELETE FROM tasks WHERE id = ?', [req.params.id]);
    
    res.json({ message: '任务已删除' });
  } catch (err) {
    console.error(err.message);
    res.status(500).json({ message: '删除任务失败' });
  }
});

module.exports = router; 